import axios from "axios";
import { ElMessage } from "element-plus";
import{useUserStore} from'@/stores/user.js'
import router from "@/router";

const httpInstance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 50000
})
// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  //获取token
  const userStore=useUserStore()
  const token=userStore.userDate.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
  ElMessage.error(e.response.data.message)
  // 401 未授权
  //1.清除用户信息
  //2.跳转到登录页面
  if (e.response.status === 401) {
    useUserStore().clearUser()
    router.push('/login')
  }
  return Promise.reject(e)
})
export default httpInstance;
